<template>
    <div class="app-container">
        <el-button type="primary" @click="handleAddRole">
        {{ $t('permission.addRole') }}
        </el-button>
        <el-table style="width: 100%;margin-top:30px;" border ref="tableCot" v-loading="loading" element-loading-text="请稍后..." :data="rolesList">
            <el-table-column :label="$t('table.id')" type="index" prop="rank" align="center" width="60" />
            <el-table-column prop="name" label="角色名" show-overflow-tooltip align="center"/>
            <el-table-column prop="rowKey" label="角色代码" show-overflow-tooltip align="center"/>
            <el-table-column prop="description" label="角色描述" min-width="120" show-overflow-tooltip align="center"/>
            <el-table-column prop="updateUser" label="创建人" show-overflow-tooltip align="center"/>
            <el-table-column prop="updateTime" label="最近更新时间" show-overflow-tooltip align="center"/>
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.isEnable?'已启用':'已禁用'" placement="top">
                        <el-switch
                                v-model="scope.row.isEnable"
                                :active-value="true"
                                :inactive-value="false"
                                @change="switchChange(scope.row)"
                        />
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-tag style="cursor:pointer;margin-right: 4px;" size="mini" @click="handleEdit(scope)">
                        <i class="el-icon-edit"/>编辑
                    </el-tag>
                    <el-tag v-if="!scope.row.isSystem" style="cursor:pointer;" size="mini" type="danger"
                            @click="handleDelete(scope)">
                        <i class="el-icon-delete"/>删除
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新增角色'">
            <el-form :model="role" label-width="80px" label-position="left">
                <el-form-item label="角色名称">
                <el-input v-model="role.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色代码">
                <el-input v-model="role.roleKey" placeholder="请输入角色代码" />
                </el-form-item>
                <el-form-item label="角色描述">
                <el-input
                    v-model="role.description"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    type="textarea"
                    placeholder="请输入角色描述"
                />
                </el-form-item>
                <el-form-item label="角色权限">
                    <el-tree ref="tree" :check-strictly="checkStrictly" :data="rolesList" :props="defaultProps" show-checkbox node-key="path" class="permission-tree" />
                </el-form-item>
            </el-form>
            <div style="text-align:right;">
                <el-button type="default" @click="dialogVisible=false">
                {{ $t('permission.cancel') }}
                </el-button>
                <el-button type="primary" @click="confirmRole">
                {{ $t('permission.confirm') }}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import path from "path";
import { deepClone } from "@/utils";
import {
  getRoutes,
  getRoles,
  addRole,
  deleteRole,
  updateRole
} from "@/api/role";
import i18n from "@/lang";

const defaultRole = {
  roleKey: "",
  name: "",
  description: "",
  routes: []
};

export default {
  name: "systemRole",
  data() {
    return {
      loading: false, 
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: "new",
      checkStrictly: false,
      defaultProps: {
        children: "children",
        label: "title"
      },
      rolesList: [
        {
          id: 1,
          name: "超级管理员",
          roleKey: "SuperAdministrator",
          description: "超级管理员，拥有至高无上的权限",
          createUser: "admin",
          updateUser: "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02",
          isEnable: true,
          permission: []
        }
      ]
    };
  },
  mounted() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
    // this.getList();
    // let that = this;
    // window.onresize = () => {
    //   //37是box的header的padding，70=(60+10)是顶部的高度
    //   let tempHeaderHeight = this.$refs.topHeader.offsetHeight + 37 + 95;
    //   let tempHeight = document.body.clientHeight - (106 + tempHeaderHeight);
    //   if (tempHeight < 300) {
    //     tempHeight = 300;
    //   }
    //   that.customTableHeight = tempHeight;
    // };
    // setTimeout(function() {
    //   const resizeEvent = new Event("resize");
    //   window.dispatchEvent(resizeEvent);
    // }, 100);
  },
//   destroyed() {
//     window.onresize = null;
//   },
  methods: {
      async getRoutes() {
      const res = await getRoutes()
      this.serviceRoutes = res.data
      const routes = this.generateRoutes(res.data)
      this.routes = this.i18n(routes)
    },
    async getRoles() {
      const res = await getRoles()
      this.rolesList = res.data
    },
    i18n(routes) {
      const app = routes.map(route => {
        route.title = i18n.t(`route.${route.title}`)
        if (route.children) {
          route.children = this.i18n(route.children)
        }
        return route
      })
      return app
    },
    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole);
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([]);
      }
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.checkStrictly = true;
      this.role = deepClone(scope.row);
      this.$nextTick(() => {
        // const routes = this.generateRoutes(this.role.routes)
        // this.$refs.tree.setCheckedNodes(this.generateArr(routes))
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false;
      });
    },
    handleDelete({ $index, row }) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteRole(row.key);
          this.rolesList.splice($index, 1);
          this.$message({
            type: "success",
            message: "Delete succed!"
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    switchChange(row) {
      const enable = row.isEnable;
      let text = "是否禁用角色？";
      if (enable) {
        text = "确认启用该角色？";
      }
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnPressEscape: false,
        closeOnClickModal: false,
        type: "warning"
      });
      //  .then(() => {
      //     roleApi.status(row.id, enable).then(res => {

      //     }).catch(() => {
      //         row.isEnable = !enable
      //     })
      // }).catch(() => {
      //     row.isEnable = !enable
      // })
    },
    getList() {
      // this.loading = true
      // roleApi.list(this.listQuery).then(res => {
      //     this.rolesList = res.data || []
      //     this.loading = false
      // }).catch(() => this.loading = false)
    },
    async confirmRole() {
      const isEdit = this.dialogType === "edit";

      const checkedKeys = this.$refs.tree.getCheckedKeys();
      this.role.routes = this.generateTree(
        deepClone(this.serviceRoutes),
        "/",
        checkedKeys
      );

      if (isEdit) {
        await updateRole(this.role.key, this.role);
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].key === this.role.key) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role));
            break;
          }
        }
      } else {
        const { data } = await addRole(this.role);
        this.role.key = data.key;
        this.rolesList.push(this.role);
      }

      const { description, key, name } = this.role;
      this.dialogVisible = false;
      this.$notify({
        title: "Success",
        dangerouslyUseHTMLString: true,
        message: `
            <div>Role Key: ${key}</div>
            <div>Role Name: ${name}</div>
            <div>Description: ${description}</div>
          `,
        type: "success"
      });
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null;
      const showingChildren = children.filter(item => !item.hidden);

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0];
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path);
        return onlyOneChild;
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: "", noShowingChildren: true };
        return onlyOneChild;
      }

      return false;
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>

